package com.lyxy.aop;
import com.alibaba.fastjson.JSONObject;
import com.lyxy.mapper.OperateLogMapper;
import com.lyxy.pojo.OperateLog;
import com.lyxy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


/**
 * @ClassName: LogAspect
 * @Description: TODO
 * 记录操作日志
 */

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.lyxy.anno.MyLog)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
//        获取请求头中jwt令牌,解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        //获取当前员工ID
        Integer operateUser = (Integer) claims.get("id");
        //获取当前时间
        LocalDateTime operateTime = LocalDateTime.now();
        //获取操作类
        String className = joinPoint.getTarget().getClass().getName();
        //获取操作方法
        String methodName = joinPoint.getSignature().getName();
        //获取操作参数
        String methodParams = joinPoint.getArgs().toString();

        //获取操作开始时间
        long startTime = System.currentTimeMillis();

        //获取操作结果
        Object value = joinPoint.proceed();
        String returnValue = JSONObject.toJSONString(value);

        //获取操作时间
        long costTime = System.currentTimeMillis()-startTime;



        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        operateLogMapper.insert(operateLog);


        log.info("操作日志记录{}",operateLog);
        return value;
    }

}
